﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System;

namespace ExameRegister
{
    public class Utility
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string ConvertToJson(object entity)
        {            
            if (entity != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(entity.GetType());
                    ser.WriteObject(ms, entity);
                    byte[] json = ms.ToArray();
                    string jsonString = Encoding.UTF8.GetString(json, 0, json.Length);//序列化得到的字符串
                    return jsonString;
                }
            }           
            return null;
        }

        public static  T ConvertFromJson<T>(string json) where T : new()
        {
            if (!string.IsNullOrEmpty(json))
            {
                byte[] bytes = Encoding.UTF8.GetBytes(json);
                using (MemoryStream ms2 = new System.IO.MemoryStream(bytes))
                {
                    ms2.Read(bytes, 0, bytes.Length);
                    DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(T));
                    T p2 = (T)ser2.ReadObject(ms2);

                    return p2;
                }
            }
            return new T();
        }

        /// <summary>
        /// 通过json方式将实体之间转换
        /// </summary>
        /// <typeparam name="T">目标实体</typeparam>
        /// <param name="entity">转换实体</param>
        /// <returns></returns>
        public static object Convert(object entity, Type t) 
        {
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(entity.GetType());
            ser.WriteObject(ms, entity);
            byte[] json = ms.ToArray();
            ms.Close();
            object p2 = null;
            using (MemoryStream ms2 = new System.IO.MemoryStream(json))
            {
                ms2.Read(json, 0, json.Length);
                DataContractJsonSerializer ser2 = new DataContractJsonSerializer(t);
                p2 = ser2.ReadObject(ms2);                
                return p2;
            }
            return p2;
        }
    }
}
